<script lang="ts" setup name="login">
/*
表单验证
1：表单元素值的绑定
2：写规则
    rules:{
      mobile:[{}]
    }
3:绑定规则
   van-filed  :rules=rules.mobile

4:触发验证
   const vanForm=ref()
   van-form  ref='vanForm'

   vanForm.value.validate().then(()=>{
    // 验证成功
   }).catch(()=>{
    // 验证失败
   })

登录接口请求
  1：表单验证
  2：定义api
  3:导入api
  4:点击确定在表单验证通过后调用
  5：定义接口的返回值类型与请求参数的类型并使用
  6：存储数据且提示

发送验证码
  1：表单验证（局部表单验证）
  2：定义api
  3:导入api
  4:定义接口返回值类型与请求参数类型并使用
  5：提示显示验证码

短信验证码登录
  1:定义接口api
  2:导入api
  3:在点击确定时要分场景调用
  4：处理数据类型

*/

import { showSuccessToast, type FieldRule, type FormInstance } from 'vant'
import { ref } from 'vue'
import { loginPassword, getCode, loginPost } from '@/api/user'
import { useRouter } from 'vue-router'
// 使用pinia
import { useUserStore } from '@/stores'
import { onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
const store = useUserStore()
const router = useRouter()
const route = useRoute()

const show = ref(false)
const mobile = ref('13211112222')
const password = ref('abc12345')
const isCheck = ref(false)
const code = ref('')
const rules: {
  mobile: FieldRule[]
  password: FieldRule[]
  isCheck: FieldRule[]
  code: FieldRule[]
} = {
  mobile: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^1[3-9]\d{9}$/, message: '请正确输入手机号', trigger: 'onChange' }
  ],
  password: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\w{6,12}$/, message: '请输入6-12位密码', trigger: 'onChange' }
  ],
  isCheck: [
    {
      validator: value => {
        return value
      },
      message: '请勾选协议',
      trigger: 'onChange'
    }
  ],
  code: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\w{6}$/, message: '请输入4位验证码', trigger: 'onChange' }
  ]
}
const form = ref<FormInstance | undefined>()
// 登录
const submit = async () => {
  await form.value!.validate()
  // 代表验证成功处理
  // if (isPass.value) {
  //   const res = await loginPassword({
  //     password: password.value,
  //     mobile: mobile.value
  //   })
  //   // 存储用户信息包括token
  //   store.setUserInfo(res.data)
  // } else {
  //   const res = await loginPost({
  //     mobile: mobile.value,
  //     code: code.value
  //   })
  //   store.setUserInfo(res.data)
  //   console.log(res)
  // }
  const res = isPass.value
    ? await loginPassword({
        password: password.value,
        mobile: mobile.value
      })
    : await loginPost({
        mobile: mobile.value,
        code: code.value
      })
  store.setUserInfo(res.data)

  // 提示
  showSuccessToast('登录成功')
  // 跳转到首页
  const back = route.query.redirect as string
  router.push(back || '/')
  // console.log('登录返回值', res)
}
// 切换
const isPass = ref(true) // true:密码登录  false:验证码登录
// 发送验证码
const time = ref(0)
let timeId = -1
// onBeforeUnmount
// vue2与vue3区别
// setup替代  beforeCreate 与created
// 都加了on 导入再使用
// 除了setup其它可多次执行
// beforeDestroy  onBeforeUnmount

const sendClick = async () => {
  await form.value?.validate('mobile')
  // 不管成功失败都有倒计时
  time.value = 5
  timeId = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      clearInterval(timeId)
    }
  }, 1000)
  // time.value = 5
  // try {
  const res = await getCode({
    mobile: mobile.value,
    type: 'login'
  })
  // 请求成功才进行倒计时
  // time.value = 5
  // clearInterval(timeId)
  // timeId = setInterval(() => {
  //   time.value--
  //   if (time.value <= 0) {
  //     clearInterval(timeId)
  //   }
  // }, 1000)

  showSuccessToast(res.data.code)
  // } finally {
  //   time.value = 0
  // }
}
const aClick = () => {
  store.setBackUrl((route.query.redirect as string) || '')
  // alert(route.query.redirect)
}
onBeforeUnmount(() => {
  clearInterval(timeId)
})
</script>

<template>
  <div class="login-page">
    <cp-nav-bar rightText="注册123" @click-right="$router.push('/register')" />
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ !isPass ? '密码登录' : '短信验证码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form autocomplete="off" ref="form">
      <van-field
        name="mobile"
        :rules="rules.mobile"
        placeholder="请输入手机号"
        type="tel"
        v-model="mobile"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        :rules="rules.password"
        placeholder="请输入密码"
        :type="`${show ? 'text' : 'password'}`"
      >
        <template #right-icon>
          <cp-icon @click="show = !show" :name="`login-eye-${show ? 'on' : 'off'}`" />
        </template>
      </van-field>
      <van-field v-else placeholder="短信验证码" v-model="code" :rules="rules.code">
        <template #button>
          <span class="send" @click="sendClick" v-if="time === 0">发送验证码</span>
          <span class="send" v-else>倒计时{{ time }}s后</span>
        </template>
      </van-field>

      <div class="cp-cell">
        <van-field :rules="rules.isCheck">
          <template #input>
            <van-checkbox v-model="isCheck">
              <span>我已同意</span>
              <a href="javascript:;">用户协议</a>
              <span>及</span>
              <a href="javascript:;">隐私条款</a>
            </van-checkbox>
          </template>
        </van-field>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" @click="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <a
        @click="aClick"
        class="icon"
        href="https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fconsult-patients.itheima.net%2Flogin%2Fcallback"
      >
        <img src="@/assets/qq.svg" alt="" />
      </a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
.send {
  color: var(--van-nav-bar-text-color);
}
</style>
